"""
S8设备协议处理器
S8 Device Protocol Handler

处理S8设备的通信协议和数据格式转换
Handles communication protocol and data format conversion for S8 devices
"""

import logging
from typing import Dict, Any, Optional
from pydantic import ValidationError

from ...interfaces.protocol_interface import ProtocolInterface
from .models import S8DataModels

logger = logging.getLogger(__name__)


class S8Protocol(ProtocolInterface):
    """
    S8设备协议处理器
    S8 Device Protocol Handler
    
    实现S8设备的协议解析和响应格式化
    Implements protocol parsing and response formatting for S8 devices
    """
    
    def __init__(self):
        """初始化S8协议处理器 / Initialize S8 protocol handler"""
        self.protocol_version = "2.0"
        self.supported_actions = ["location", "health", "battery", "sensor", "alert", "status"]
        self.logger = logging.getLogger(f"{self.__class__.__name__}")
    
    async def parse_request(self, raw_data: Dict[str, Any]) -> Optional[Any]:
        """
        解析S8设备请求数据
        Parse S8 device request data
        
        Args:
            raw_data (Dict[str, Any]): 原始请求数据 / Raw request data
            
        Returns:
            Optional[Any]: 解析后的数据模型 / Parsed data model
            
        Raises:
            ValidationError: 数据验证失败 / Data validation failed
        """
        try:
            # S8设备数据可能没有明确的action字段，需要推断数据类型
            # S8 device data may not have explicit action field, need to infer data type
            data_type = raw_data.get("type") or raw_data.get("action")
            
            if not data_type:
                # 尝试根据数据内容推断类型 / Try to infer type based on data content
                data_type = S8DataModels.infer_data_type(raw_data)
                if not data_type:
                    self.logger.error("无法确定S8数据类型 / Cannot determine S8 data type")
                    return None
            
            # 获取对应的数据模型 / Get corresponding data model
            model_class = S8DataModels.get_model(data_type)
            if not model_class:
                self.logger.error(f"不支持的S8数据类型: {data_type} / Unsupported S8 data type: {data_type}")
                return None
            
            # 验证和转换数据 / Validate and convert data
            validated_data = model_class(**raw_data)
            self.logger.info(f"成功解析S8 {data_type}数据 / Successfully parsed S8 {data_type} data")
            
            return validated_data
            
        except ValidationError as e:
            self.logger.error(f"S8数据验证失败 / S8 data validation failed: {str(e)}")
            raise
        except Exception as e:
            self.logger.error(f"解析S8请求数据时发生错误 / Error occurred while parsing S8 request data: {str(e)}")
            return None
    
    async def format_response(self, data: Any) -> Dict[str, Any]:
        """
        格式化S8设备响应数据
        Format S8 device response data
        
        Args:
            data (Any): 响应数据 / Response data
            
        Returns:
            Dict[str, Any]: 格式化后的响应 / Formatted response
        """
        try:
            # S8设备使用不同的响应格式 / S8 devices use different response format
            if isinstance(data, dict):
                return {
                    "flag": data.get("flag", 1),  # S8使用flag字段 / S8 uses flag field
                    "msg": data.get("msg", "成功 / Success"),
                    "obj": data.get("obj", {"test": 1})
                }
            else:
                # 默认成功响应格式 / Default success response format
                return {
                    "flag": 1,
                    "msg": "成功 / Success",
                    "obj": data if data else {"test": 1}
                }
                
        except Exception as e:
            self.logger.error(f"格式化S8响应数据时发生错误 / Error occurred while formatting S8 response data: {str(e)}")
            return {
                "flag": 0,
                "msg": f"响应格式化失败 / Response formatting failed: {str(e)}",
                "obj": {}
            }
    
    async def validate_request(self, data: Dict[str, Any]) -> bool:
        """
        验证S8设备请求数据
        Validate S8 device request data
        
        Args:
            data (Dict[str, Any]): 请求数据 / Request data
            
        Returns:
            bool: 验证结果 / Validation result
        """
        try:
            # S8设备的验证规则较为宽松 / Validation rules for S8 devices are more lenient
            
            # 检查是否有有效的数据类型指示 / Check if there's valid data type indication
            data_type = data.get("type") or data.get("action")
            if not data_type:
                # 尝试推断数据类型 / Try to infer data type
                data_type = S8DataModels.infer_data_type(data)
                if not data_type:
                    self.logger.error("无法确定S8数据类型 / Cannot determine S8 data type")
                    return False
            
            # 检查数据类型是否支持 / Check if data type is supported
            if not S8DataModels.validate_data_type(data_type):
                self.logger.error(f"不支持的S8数据类型: {data_type} / Unsupported S8 data type: {data_type}")
                return False
            
            # 检查设备ID（如果存在）/ Check device ID (if exists)
            device_id = data.get("device_id") or data.get("imei") or data.get("deviceId")
            if device_id and not isinstance(device_id, str):
                self.logger.error("设备ID格式错误 / Invalid device ID format")
                return False
            
            self.logger.debug("S8请求数据验证通过 / S8 request data validation passed")
            return True
            
        except Exception as e:
            self.logger.error(f"验证S8请求数据时发生错误 / Error occurred while validating S8 request data: {str(e)}")
            return False
    
    def get_protocol_version(self) -> str:
        """
        获取协议版本
        Get protocol version
        
        Returns:
            str: 协议版本 / Protocol version
        """
        return self.protocol_version
    
    def get_supported_actions(self) -> list:
        """
        获取支持的操作类型
        Get supported action types
        
        Returns:
            list: 支持的操作列表 / List of supported actions
        """
        return self.supported_actions.copy()
    
    async def format_error_response(self, error_code: int, error_message: str) -> Dict[str, Any]:
        """
        格式化错误响应
        Format error response
        
        Args:
            error_code (int): 错误代码 / Error code
            error_message (str): 错误消息 / Error message
            
        Returns:
            Dict[str, Any]: 错误响应 / Error response
        """
        return {
            "flag": 0,
            "error_code": error_code,
            "msg": error_message,
            "obj": {}
        }
    
    async def normalize_device_data(self, raw_data: Dict[str, Any]) -> Dict[str, Any]:
        """
        标准化设备数据格式
        Normalize device data format
        
        Args:
            raw_data (Dict[str, Any]): 原始数据 / Raw data
            
        Returns:
            Dict[str, Any]: 标准化后的数据 / Normalized data
        """
        try:
            normalized_data = raw_data.copy()
            
            # 统一设备ID字段 / Unify device ID field
            device_id = raw_data.get("device_id") or raw_data.get("imei") or raw_data.get("deviceId")
            if device_id:
                normalized_data["device_id"] = device_id
            
            # 统一时间戳字段 / Unify timestamp field
            timestamp = raw_data.get("timestamp") or raw_data.get("time") or raw_data.get("ts")
            if timestamp:
                normalized_data["timestamp"] = timestamp
            
            # 添加数据类型字段 / Add data type field
            if "type" not in normalized_data and "action" not in normalized_data:
                inferred_type = S8DataModels.infer_data_type(raw_data)
                if inferred_type:
                    normalized_data["type"] = inferred_type
            
            self.logger.debug("S8数据标准化完成 / S8 data normalization completed")
            return normalized_data
            
        except Exception as e:
            self.logger.error(f"标准化S8数据时发生错误 / Error occurred while normalizing S8 data: {str(e)}")
            return raw_data